package com.invoicerecognition.backend.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class OkHttpUtil {

    private OkHttpUtil() {
    }

    private static final class HttpClientHolder {
        public static final OkHttpClient httpClient = new OkHttpClient().newBuilder()
                .connectTimeout(2000, TimeUnit.MILLISECONDS)
                .readTimeout(5000, TimeUnit.MILLISECONDS)
                .writeTimeout(2000, TimeUnit.MILLISECONDS)
                .build();
    }

    public static OkHttpClient getInstance() {
        return HttpClientHolder.httpClient;
    }

    public static Response doPost(String url, JSONObject reqObj) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), reqObj.toJSONString()))
                .build();
        return getInstance().newCall(request).execute();
    }

    public static Response doGet(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        return getInstance().newCall(request).execute();
    }
}